<template>
  <div class="volunteer-apply-container">
    <div class="form-card">
      <h2 class="form-title">志愿者申请表</h2>

      <!-- 状态提示 -->
      <div v-if="applicationStatus" class="status-alert" :class="`status-${applicationStatus.type}`">
        <div class="alert-icon">
          <span v-if="applicationStatus.type === 'info'">ℹ️</span>
          <span v-if="applicationStatus.type === 'warning'">⚠️</span>
          <span v-if="applicationStatus.type === 'error'">❌</span>
          <span v-if="applicationStatus.type === 'success'">✅</span>
        </div>
        <div class="alert-content">
          <h4>{{ applicationStatus.title }}</h4>
          <p>{{ applicationStatus.message }}</p>
          <button
            v-if="applicationStatus.showReapply"
            @click="handleReapply"
            class="btn-reapply"
          >
            重新申请
          </button>
        </div>
      </div>

      <!-- 申请表单 -->
      <form v-if="canApply" @submit.prevent="handleSubmit" class="apply-form">
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">姓名</label>
            <input
              type="text"
              v-model="formData.name"
              class="form-control"
              disabled
            >
            <div class="form-hint">从用户信息自动获取</div>
          </div>

          <div class="form-group">
            <label class="form-label">电话</label>
            <input
              type="tel"
              v-model="formData.phone"
              class="form-control"
              disabled
            >
            <div class="form-hint">从用户信息自动获取</div>
          </div>

          <div class="form-group">
            <label class="form-label">邮箱</label>
            <input
              type="email"
              v-model="formData.email"
              class="form-control"
              disabled
            >
            <div class="form-hint">从用户信息自动获取</div>
          </div>

          <div class="form-group">
            <label class="form-label">部门 <span class="required">*</span></label>
            <select
              v-model="formData.department"
              class="form-control"
              required
              :disabled="!canApply"
            >
              <option value="">请选择部门</option>
              <option value="活动策划部">活动策划部</option>
              <option value="现场执行部">现场执行部</option>
              <option value="宣传推广部">宣传推广部</option>
              <option value="后勤保障部">后勤保障部</option>
              <option value="医疗救护部">医疗救护部</option>
              <option value="志愿者管理部">志愿者管理部</option>
              <option value="其他">其他</option>
            </select>
          </div>

          <div class="form-group">
            <label class="form-label">职位 <span class="required">*</span></label>
            <select
              v-model="formData.position"
              class="form-control"
              required
              :disabled="!canApply"
            >
              <option value="">请选择职位</option>
              <option value="普通志愿者">普通志愿者</option>
              <option value="小组长">小组长</option>
              <option value="部门助理">部门助理</option>
              <option value="活动协调员">活动协调员</option>
              <option value="其他">其他</option>
            </select>
          </div>

          <div class="form-group full-width">
            <label for="experience" class="form-label">相关经历 <span class="required">*</span></label>
            <textarea
              id="experience"
              v-model="formData.experience"
              class="form-control textarea"
              :class="{ 'is-invalid': errors.experience }"
              rows="4"
              placeholder="请描述您参与过的志愿者活动或相关经验"
              required
              :disabled="!canApply"
            ></textarea>
            <div class="error-message" v-if="errors.experience">{{ errors.experience }}</div>
          </div>
        </div>

        <div class="form-actions">
          <button type="submit" class="btn btn-submit" :disabled="isSubmitting || !canApply">
            <span v-if="!isSubmitting">提交申请</span>
            <span v-if="isSubmitting">提交中...</span>
          </button>
          <button type="button" class="btn btn-cancel" @click="handleCancel">
            取消
          </button>
        </div>
      </form>
    </div>

    <!-- 成功提示弹窗 -->
    <div v-if="showSuccess" class="modal-overlay">
      <div class="modal success-modal">
        <div class="success-icon">✓</div>
        <h3 class="success-title">提交成功！</h3>
        <p class="success-message">
          您的志愿者申请已成功提交，请等待审核结果。
        </p>
        <button @click="showSuccess = false; $emit('application-submitted');" class="btn btn-confirm">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { request } from '@/utils/request';

// 表单数据类型
interface VolunteerForm {
  name: string;
  phone: string;
  email: string;
  department: string;
  position: string;
  experience: string;
}

// 用户信息响应类型
interface UserApiResponse {
  userID: number;
  username: string;
  phone: string;
  email: string;
  department: string;
  grade: string;
  major: string;
  createTime: string;
}

interface UserInfoResponse {
  success: boolean;
  message?: string;
  user?: UserApiResponse;
}

// 申请状态类型
interface ApplicationStatus {
  type: 'info' | 'warning' | 'error' | 'success';
  title: string;
  message: string;
  showReapply?: boolean;
}

// 志愿者申请类型
interface VolunteerApplication {
  volunteerID?: number;
  userID: number;
  name: string;
  phone: string;
  email: string;
  department: string;
  position: string;
  experience: string;
  status: string;
  applyTime: string;
  reviewNotes?: string;
}

// 定义事件
const emit = defineEmits<{
  (e: 'application-submitted'): void;
  (e: 'cancel'): void;
}>();

// 响应数据
const formData = ref<VolunteerForm>({
  name: '',
  phone: '',
  email: '',
  department: '',
  position: '',
  experience: ''
});

const errors = ref<Record<string, string>>({});
const isSubmitting = ref(false);
const showSuccess = ref(false);
const applicationStatus = ref<ApplicationStatus | null>(null);
const currentApplication = ref<VolunteerApplication | null>(null);

// 计算属性：是否可以申请
const canApply = computed(() => {
  if (!currentApplication.value) return true;
  if (currentApplication.value.status === 'rejected') return true;
  return false;
});

// 加载用户信息和申请状态
const loadUserInfoAndStatus = async (): Promise<void> => {
  try {
    const userId = localStorage.getItem('userId');
    if (!userId) return;

    // 加载用户信息
    const userResponse: UserInfoResponse = await request.get('/api/user/info', {
      params: { userId: parseInt(userId) }
    });

    if (userResponse.success && userResponse.user) {
      const userData = userResponse.user;
      formData.value = {
        name: userData.username || '',
        phone: userData.phone || '',
        email: userData.email || '',
        department: userData.department || '',
        position: '',
        experience: ''
      };
    }

    // 检查申请状态
    await checkApplicationStatus();
  } catch (error) {
    console.error('加载用户信息失败:', error);
  }
};

// 检查申请状态
const checkApplicationStatus = async (): Promise<void> => {
  try {
    const response = await request.get<{
      success: boolean;
      message?: string;
      application?: VolunteerApplication;
    }>('/api/volunteer/my-application');

    console.log('申请状态检查:', response);

    if (response.success) {
      currentApplication.value = response.application || null;

      if (response.application) {
        const status = response.application.status;
        if (status === 'pending') {
          applicationStatus.value = {
            type: 'warning',
            title: '申请审核中',
            message: '您已经提交过志愿者申请，请等待审核'
          };
        } else if (status === 'approved') {
          applicationStatus.value = {
            type: 'success',
            title: '已经是志愿者',
            message: '您已经是志愿者，无需重复申请'
          };
        } else if (status === 'rejected') {
          applicationStatus.value = {
            type: 'error',
            title: '申请未通过',
            message: '您的志愿者申请未通过审核，可以重新提交申请',
            showReapply: true
          };
        }
      } else {
        applicationStatus.value = null;
      }
    }
  } catch (error) {
    console.error('检查申请状态失败:', error);
  }
};

// 表单验证
const validateForm = (): boolean => {
  const newErrors: Record<string, string> = {};

  if (!formData.value.department.trim()) {
    newErrors.department = '请选择部门';
  }

  if (!formData.value.position.trim()) {
    newErrors.position = '请选择职位';
  }

  if (!formData.value.experience.trim()) {
    newErrors.experience = '请填写相关经历';
  }

  errors.value = newErrors;
  return Object.keys(newErrors).length === 0;
};

// 提交表单
const handleSubmit = async (): Promise<void> => {
  if (!validateForm()) {
    return;
  }

  isSubmitting.value = true;

  try {
    const userId = localStorage.getItem('userId');
    if (!userId) {
      alert('未检测到用户信息，请重新登录');
      return;
    }

    const submitData = {
      userID: parseInt(userId),
      name: formData.value.name,
      phone: formData.value.phone,
      email: formData.value.email,
      department: formData.value.department,
      position: formData.value.position,
      experience: formData.value.experience
    };

    console.log('提交志愿者申请:', submitData);
    const response = await request.post('/api/volunteer/apply', submitData);
    console.log('提交响应:', response);

    if (response.success) {
      showSuccess.value = true;
      // 清空表单
      formData.value = {
        name: '',
        phone: '',
        email: '',
        department: '',
        position: '',
        experience: ''
      };
      errors.value = {};
      // 重新检查申请状态
      await checkApplicationStatus();
    } else {
      alert(`提交失败：${response.message}`);
    }
  } catch (error) {
    console.error('提交申请失败:', error);
    alert('提交失败，请稍后重试');
  } finally {
    isSubmitting.value = false;
  }
};

// 重新申请
const handleReapply = () => {
  applicationStatus.value = null;
  currentApplication.value = null;
};

// 取消功能
const handleCancel = (): void => {
  emit('cancel');
};

// 初始化加载用户信息
onMounted(() => {
  loadUserInfoAndStatus();
});
</script>

<style scoped>
/* 状态提示样式 */
.status-alert {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 24px;
  border: 1px solid;
}

.status-info {
  background: #e6f7ff;
  border-color: #91d5ff;
  color: #0050b3;
}

.status-warning {
  background: #fffbe6;
  border-color: #ffe58f;
  color: #d48806;
}

.status-error {
  background: #fff2f0;
  border-color: #ffccc7;
  color: #d4380d;
}

.status-success {
  background: #f6ffed;
  border-color: #b7eb8f;
  color: #389e0d;
}

.alert-icon {
  font-size: 20px;
  margin-right: 12px;
  margin-top: 2px;
}

.alert-content h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
}

.alert-content p {
  margin: 0 0 12px 0;
  font-size: 14px;
  line-height: 1.5;
}

.btn-reapply {
  padding: 6px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-reapply:hover {
  background: #096dd9;
}

/* 原有样式保持不变 */
.volunteer-apply-container {
  width: 100%;
  height: 100%;
}

.form-card {
  background: white;
  border-radius: 15px;
  padding: 40px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow-y: auto;
}

.form-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 2rem;
  font-weight: 600;
  background: linear-gradient(to right, #31B310, #3498db);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #495057;
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #ff4d4f;
  font-weight: bold;
}

.form-control {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #fff;
}

.form-control:focus {
  outline: none;
  border-color: #31B310;
  box-shadow: 0 0 0 3px rgba(49, 179, 16, 0.1);
  transform: translateY(-1px);
}

.form-control:disabled {
  background-color: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
  border-color: #dee2e6;
}

.form-control.is-invalid {
  border-color: #ff4d4f;
  box-shadow: 0 0 0 3px rgba(255, 77, 79, 0.1);
}

.textarea {
  resize: vertical;
  min-height: 100px;
  font-family: inherit;
}

.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #6c757d;
  line-height: 1.4;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 6px;
  min-height: 16px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f2f5;
}

.btn {
  padding: 12px 32px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 140px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.btn-submit {
  background: linear-gradient(135deg, #31B310, #2a990e);
  color: white;
}

.btn-submit:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  background: linear-gradient(135deg, #2a990e, #248f0c);
}

.btn-submit:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-cancel {
  background: linear-gradient(135deg, #6c757d, #5a6268);
  color: white;
}

.btn-cancel:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  background: linear-gradient(135deg, #5a6268, #495057);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.success-modal {
  background-color: white;
  border-radius: 15px;
  padding: 40px;
  text-align: center;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.success-icon {
  font-size: 64px;
  color: #52c41a;
  margin-bottom: 20px;
}

.success-title {
  color: #2c3e50;
  margin-bottom: 16px;
  font-size: 1.5rem;
  font-weight: 600;
}

.success-message {
  color: #666;
  margin-bottom: 30px;
  line-height: 1.6;
}

.btn-confirm {
  background: linear-gradient(135deg, #31B310, #2a990e);
  color: white;
  padding: 10px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.btn-confirm:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

@media (max-width: 768px) {
  .form-card {
    padding: 30px 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .form-title {
    font-size: 1.5rem;
  }

  .form-actions {
    flex-direction: column;
    gap: 10px;
  }

  .btn {
    width: 100%;
  }
}
</style>
